package xin.examinationSystem.servlet;

import com.alibaba.fastjson.JSON;
import xin.examinationSystem.account.Student;
import xin.examinationSystem.account.Teacher;
import xin.examinationSystem.account.testPaper.Location_table;
import xin.examinationSystem.account.testPaper.TP_Title;
import xin.examinationSystem.account.testPaper.TestPaper;
import xin.examinationSystem.account.testPaper.StuLookTestPaperSet;
import xin.examinationSystem.account.testPaper.topic.*;
import xin.examinationSystem.dao.IStudentMapper;
import xin.examinationSystem.dao.topic.ITestPaperMapper;
import xin.examinationSystem.imp.TestPaperMapperImp;
import xin.examinationSystem.utils.Tools;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;

@WebServlet("/stuQueryTestPaperServlet")
public class stuQueryTestPaperServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean studentStatus = false;
        Student curStudent = new Student();
        Cookie[] cookies = request.getCookies();
        for (Cookie tCookie : cookies) {
            if (tCookie.getName().equals("accountMessageStudent")) {
                HttpSession session = request.getSession();
                curStudent = (Student) session.getAttribute(tCookie.getValue());
                if (curStudent != null) {
                    studentStatus = true;
                }
            }
        }

        if (!studentStatus) {
            response.sendRedirect("/index.html");
            return;
        }

        ITestPaperMapper iTestPaperMapper = (ITestPaperMapper) Tools.getImp("ITestPaperMapper");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        //返回所有题目数量
        String query_all_topic = request.getParameter("query_all_topic");
        if (query_all_topic != null) {
            out.write(TestPaperMapperImp.queryAllTopic());
            out.flush();
            out.close();
            return;
        }

        //返回所有题目数量
        String get_my_stuId = request.getParameter("get_my_stuId");
        if (get_my_stuId != null) {
            out.write("" + curStudent.getStuId());
            out.flush();
            out.close();
            return;
        }

        //返回所有题目数量
        String query_all_Student_test_paper = request.getParameter("query_all_Student_test_paper");
        if (query_all_Student_test_paper != null) {
            Student_test_paper[] stp = iTestPaperMapper.query_all_Student_test_paper(Integer.parseInt(query_all_Student_test_paper));
            if (stp.length == 0) {
                out.write("null");
                out.flush();
                out.close();
            }

            String[] resultSet = new String[stp.length];
            IStudentMapper iStudentMapper = (IStudentMapper) Tools.getImp("IStudentMapper");
            for (int index = 0, len = stp.length; index < len; index++) {
                resultSet[index] = "" + stp[index].getTpId() + "###" + stp[index].getStuId()
                        + "###" + iStudentMapper.findStuId(stp[index].getStuId()).getStuName() + "###" + stp[index].getGrade();
            }

            out.write(JSON.toJSONString(resultSet));
            out.flush();
            out.close();
            return;
        }

        //返回当前时间
        String query_current_time = request.getParameter("query_current_time");
        if (query_current_time != null) {
            //发送当前
            out.write("" + new Date().getTime());
            out.flush();
            out.close();
            return;
        }

        //返回考试时间
        String query_testPaper_time = request.getParameter("query_testPaper_time");
        if (query_testPaper_time != null) {
            System.out.println("-----------------------------------------------------------");
            TestPaper curTestPaper = iTestPaperMapper.getCurTestPaper();
            String time = curTestPaper.getStartTime().getTime() + "#####" + curTestPaper.getEntTime().getTime();
            //发送考试的时间
            System.out.println("返回的考试时间:" + curTestPaper.getStartTime().getTime() + "  " + curTestPaper.getEntTime().getTime());
            out.write(time);
            out.flush();
            out.close();
            return;
        }

        //返回考试试卷
        String query_testPaper_node = request.getParameter("query_testPaper_node");
        if (query_testPaper_node != null) {
            TestPaper testPaper = iTestPaperMapper.getCurTestPaper();
            Date curTime = new Date();

            if (curTime.getTime() < testPaper.getStartTime().getTime()) {
                out.write("no_beginning");
                out.flush();
                out.close();
                return;
            } else if (curTime.getTime() > testPaper.getEntTime().getTime()) {
                out.write("already_over");
                out.flush();
                out.close();
                return;
            }

            TestPaper curTestPaper = iTestPaperMapper.getCurTestPaper();
            Location_table lt = new Location_table(curStudent.getStuId(), curTestPaper.getId(), getIpAddr(request));

            //查询该考生是否在其它设备上已经登录
            Location_table location_table = iTestPaperMapper.query_location_table(lt);
            if (location_table != null) {
                if (!location_table.getIp().equals(getIpAddr(request))) {
                    out.write("other_location###" + location_table.getIp());
                    out.flush();
                    out.close();
                    return;
                }
            } else {
                //第一次登录，添加进地址判定表
                iTestPaperMapper.addLocation_table(new Location_table(curStudent.getStuId(), curTestPaper.getId(), getIpAddr(request)));
            }

            Student_test_paper stp = new Student_test_paper();
            //添加学生编号
            stp.setStuId(curStudent.getStuId());

            //添加试卷编号
            stp.setTpId(testPaper.getId());

            //添加考试内容
            stp.setNode(TestPaperMapperImp.createTestPaperJson(getIpAddr(request), curTestPaper.getNode()));

            //发送考试的时间
            out.write(JSON.toJSONString(stp));
            out.flush();
            out.close();
            return;
        }

        //根据试卷编号和学生编号查询学生考试信息
        String query_studentTestPaper = request.getParameter("query_studentTestPaper");
        if (query_studentTestPaper != null) {
            String[] strSet = query_studentTestPaper.split("###");
            System.out.println("收到的信息是:" + query_studentTestPaper);
            Student_test_paper[] stp = iTestPaperMapper.query_student_test_paper_stuId_and_tpId(Integer.parseInt(strSet[1]), Integer.parseInt(strSet[0]));
            if (stp == null || stp.length == 0) {
                out.write("not_found");
                out.flush();
                out.close();
                return;
            }

            //返回该考生的试卷
            out.write(JSON.toJSONString(stp[0]));
            out.flush();
            out.close();
            return;
        }

        //返回当前试卷的id
        String query_curTestPaperId = request.getParameter("query_curTestPaperId");
        if (query_curTestPaperId != null) {
            if (iTestPaperMapper.getCurTestPaper().getId() == null) {
                out.write("not_found");
                out.flush();
                out.close();
                return;
            }

            //返回当前试卷的id
            out.write("" + iTestPaperMapper.getCurTestPaper().getId());
            out.flush();
            out.close();
            return;
        }

        //查询试卷标题
        String query_TP_title = request.getParameter("query_TP_title");
        if (query_TP_title != null) {
            TP_Title tp_title = iTestPaperMapper.query_TP_title(Integer.parseInt(query_TP_title));
            out.write(tp_title.getHeadline() + "###" + tp_title.getSubtitle());
            out.flush();
            out.close();
            return;
        }

        //查询试卷标题
        String set_tpGrade = request.getParameter("set_tpGrade");
        if (set_tpGrade != null) {
            String[] nodes = set_tpGrade.split("###");
            System.out.println(Arrays.toString(nodes));
            iTestPaperMapper.set_TP_grade(Integer.parseInt(nodes[0]), Integer.parseInt(nodes[1]), Integer.parseInt(nodes[2]));
            out.write("OK");
            out.flush();
            out.close();
            return;
        }

        //查询试卷标题
        String get_curTPId = request.getParameter("get_curTPId");
        if (get_curTPId != null) {
            TestPaper curTestPaper = iTestPaperMapper.getCurTestPaper();
            if (curTestPaper == null) {
                out.write("empty");
                out.flush();
                out.close();
                return;
            }

            out.write("" + curTestPaper.getId());
            out.flush();
            out.close();
            return;
        }

        //查询试卷标题
        String query_not_correct_TP = request.getParameter("query_not_correct_TP");
        if (query_not_correct_TP != null) {
            Student_test_paper[] student_test_papers = iTestPaperMapper.query_not_correct_TP(Integer.parseInt(query_not_correct_TP));
            if (student_test_papers.length == 0) {
                out.write("empty");
                out.flush();
                out.close();
                return;
            }

            out.write("" + student_test_papers[0].getStuId());
            out.flush();
            out.close();
            return;
        }

        //查询每场的试卷信息
        String query_all_tpSet = request.getParameter("query_all_tpSet");
        if (query_all_tpSet != null) {
            StuLookTestPaperSet[] StuLookTestPaperSets = iTestPaperMapper.query_stu_all_tpSet(curStudent.getStuId());
            if (StuLookTestPaperSets == null || StuLookTestPaperSets.length == 0) {
                out.write("null");
                out.flush();
                out.close();
                return;
            }

            out.write(JSON.toJSONString(StuLookTestPaperSets));
            out.flush();
            out.close();
            return;
        }

        out.write("fail");
        out.flush();
        out.close();
    }

    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            return "192.168.32.3";
        }
        return ip;
    }
}
